package com.seckill.mapper;


import com.seckill.pojo.entity.SeckillProduct;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 秒杀特价农产品Mapper接口
 */
@Mapper
public interface SeckillProductMapper {

    /**
     * 新增秒杀特价农产品
     * @param seckillProduct
     */
    @Insert("INSERT INTO seckill_product (name, original_price, seckill_price, description, image, activity_id, stock, sold_count, limit_count, create_time, update_time, create_user, update_user) " +
            "VALUES (#{name}, #{originalPrice}, #{seckillPrice}, #{description}, #{image}, #{activityId}, #{stock}, #{soldCount}, #{limitCount}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(SeckillProduct seckillProduct);

    /**
     * 根据活动id查询秒杀特价农产品
     * @param activityId
     * @return
     */
    @Select("<script>" +
            "SELECT * FROM seckill_product " +
            "<where>" +
            "<if test='activityId != null'>" +
            "activity_id = #{activityId}" +
            "</if>" +
            "</where>" +
            "ORDER BY create_time DESC" +
            "</script>")
    List<SeckillProduct> pageQuery(@Param("activityId") Long activityId);

    /**
     * 根据id查询秒杀特价农产品
     * @param id
     * @return
     */
    @Select("SELECT * FROM seckill_product WHERE id = #{id}")
    SeckillProduct getById(Long id);

    /**
     * 修改秒杀特价农产品
     * @param seckillProduct
     */
    @Update("UPDATE seckill_product SET name = #{name}, original_price = #{originalPrice}, seckill_price = #{seckillPrice}, " +
            "description = #{description}, image = #{image}, activity_id = #{activityId}, stock = #{stock}, " +
            "sold_count = #{soldCount}, limit_count = #{limitCount}, update_time = #{updateTime}, update_user = #{updateUser} " +
            "WHERE id = #{id}")
    void update(SeckillProduct seckillProduct);

    /**
     * 删除秒杀特价农产品
     * @param id
     */
    @Delete("DELETE FROM seckill_product WHERE id = #{id}")
    void delete(Long id);

    /**
     * 扣减库存
     * @param id
     * @param count
     * @return
     */
    @Update("UPDATE seckill_product SET stock = stock - #{count}, sold_count = sold_count + #{count} WHERE id = #{id} AND stock >= #{count}")
    int reduceStock(@Param("id") Long id, @Param("count") Integer count);
}